package com.sky.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserOrderMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.UserOrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zcf
 */
@RestController
@RequestMapping("/user/order")
@Api(tags = "C端-订单接口")
@Slf4j
public class UserOrderController {

    @Resource
    private UserOrderService userOrderService;

    @Resource
    private UserOrderMapper userOrderMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     */
    @PostMapping("submit")
    @ApiOperation("用户下单")
    public Result<OrderSubmitVO> submit(@RequestBody OrdersSubmitDTO ordersSubmitDTO) {
        OrderSubmitVO orderSubmitVO = userOrderService.submit(ordersSubmitDTO);
        return Result.success(orderSubmitVO);
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @PutMapping("/payment")
    @ApiOperation("订单支付")
    public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) {
        log.info("订单支付：{}", ordersPaymentDTO);
        OrderPaymentVO orderPaymentVO = userOrderService.payment(ordersPaymentDTO);
        log.info("生成预支付交易单：{}", orderPaymentVO);
        paySuccess(ordersPaymentDTO.getOrderNumber());
        shoppingCartMapper.clean(BaseContext.getCurrentId());
        return Result.success(orderPaymentVO);
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param number
     */
    public void paySuccess(String number) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = userOrderMapper.getByNumberAndUserId(number, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        userOrderMapper.update(orders);
        //推送消息给管理端，提醒有新的订单生成
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + number);
        log.info("推送消息：" + map);
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }


    /**
     * 查看历史订单
     */
    @GetMapping("/historyOrders")
    @ApiOperation("查看历史订单")
    public Result<PageResult> historyOrders(int page, int pageSize, Integer status) {
        PageResult pageResult = userOrderService.list(page, pageSize, status);
        return Result.success(pageResult);
    }


    /**
     * 订单详情
     */
    @GetMapping("/orderDetail/{id}")
    @ApiOperation("订单详情")
    public Result<Orders> orderDetail(@PathVariable Long id) {
        OrderVO orderVO = userOrderService.getById(id);
        return Result.success(orderVO);
    }


    /**
     * 取消订单
     */
    @PutMapping("/cancel/{id}")
    @ApiOperation("取消订单")
    public Result cancel(@PathVariable Long id) {
        userOrderService.cancel(id);
        return Result.success();
    }


    /**
     * 再来一单
     */
    @PostMapping("/repetition/{id}")
    @ApiOperation("再来一单")
    public Result repetition(@PathVariable Long id) {
        userOrderService.repetition(id);
        return Result.success();
    }


    /**
     * 用户催单
     */
    @GetMapping("/reminder/{id}")
    @ApiOperation("用户催单")
    public Result reminder(@PathVariable Long id) {
        log.info("用户催单");
        OrderVO orderVO = userOrderService.getById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", orderVO.getId());
        map.put("content", "订单号：" + orderVO.getNumber());
        log.info("推送消息：" + map);
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
        return Result.success();
    }

}
